<?php

namespace RTSCraft\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use RTSCraft\MainBundle\Controller\Util\AuthUtil;
use RTSCraft\MainBundle\Entity\User;

class AdminController extends Controller
{
  private function getShort($version)
  {
	  $text = $version->getText();
	  $firstParagraphEnd = strpos($text, "</p>");

	  /* No paragraph found, take 400 characters */
	  if ($firstParagraphEnd === FALSE)
	    {
	      $firstParagraphEnd = 400;
	    }

	  $new_text = substr($text, 0, $firstParagraphEnd);

	  if (strlen($text) > $firstParagraphEnd)
	    $new_text = $new_text . '[...]';

	  return $new_text;
  }
    /**
     * @Route("/", name="homepage")
     * @Template()
     */
    public function indexAction()
    {
      // first time ? (user not defined)
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:User');
      $users = $rep->findUser();

      if (empty($users))
	{
	  // no user in database, launch install procedure !
	  return $this->render('RTSCraftMainBundle:Admin:install.html.twig');
	}
    }

    /**
     * @Route("/show", name="show")
     * @Template()
     */
    public function showAction()
    {
      // show latest modifications
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Version');
      $results = $rep->findLast();

      if (empty($results))
	{
	  $auth = AuthUtil::is_auth($this);
	  if ($auth > 0)
	    {
	      return new Response("<h4>Aucun article détecté, contactez l'administrateur de ce site</h4>");
	    }
	  else
	    {
	      return new Response('<h4>Aucun article détecté dans la base de données, <a href="#" onclick="submitForm(\'management\')">ajoutez des entités</a> ou <a href="#" onclick="submitForm(\'edition\')">créez des articles</a> !</h4>');
	    }
	}


      foreach($results as $version)
	{
	  $version->setText($this->getShort($version));
	}

      return $this->render('RTSCraftMainBundle:Default:show.html.twig', array('result' => $results));
    }

    /**
     * @Route("/history/{name}", name="history")
     * @Template()
     */
    public function historyAction($name)
    {
      $auth = AuthUtil::is_auth($this);
      if ($auth > 0)
	{
	  return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => 'Non connecté.', 'code' => $auth));
	}

      // show latest modifications on an article
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:Article');
      $versions = $rep->getVersions($name);

      /*
      foreach ($versions as $version)
	{
	  $version->setText($this->getShort($version));
	}
      */

      return $this->render('RTSCraftMainBundle:Default:history.html.twig', array('versions' => $versions));
    }

    /**
     * @Route("/change_password", name="chgpwd")
     * @Template()
     */
    public function chgpwdAction()
    {
      $auth = AuthUtil::is_auth($this);
      if ($auth > 0)
	{
	  return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => 'Non connecté.', 'code' => $auth));
	}
       return $this->render('RTSCraftMainBundle:Admin:chgpwd.html.twig');
    }

    public function passwordAction()
    {
      //called after submitting the form
      $request = $this->get('request');

      $oldpwd = "";
      $newpwd = "";
      $newpwd2 = "";

      // change password
      if ($request->getMethod() == 'POST')
	{
	  //get the data submitted
	  $oldpwd = $request->request->get('oldpwd');
	  $newpwd = $request->request->get('newpwd1');
	  $newpwd2 = $request->request->get('newpwd2');
	}

      /* -----------------------------------
       * -- check that the data are valid --
       * -----------------------------------
       */
      $oldpwd = md5($oldpwd);

      //FIXME : there is only 1 user, the admin ...
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:User');
      $users = $rep->findUser();

      //$users is an array ... of 1 element. Get the first element.
      $user = reset($users);
      $passindb = $user->getPassword();

      if ($passindb != $oldpwd)
	{
	  //error !
	  $error = 'Incorrect password.';
	  return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error));
	}

      if ($newpwd != $newpwd2)
	{
	  $error = 'The password provided are different !';
	  return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error));
	}

      if ($newpwd == "")
	{
	  $error = 'No password provided !';
	  return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error));
	}

      //all the tests passed, update in db !
      $em = $this->getDoctrine()->getEntityManager();
      $newpwd = md5($newpwd);
      $user->setPassword($newpwd);
      $em->persist($user);
      $em->flush();

      return $this->render('RTSCraftMainBundle:Default:mainFrame.html.twig');
    }

    /* Login popup */
    public function loginAction()
    {
      $is_auth = AuthUtil::is_auth($this);

      if ($is_auth == 0)
	{
	  $response = '<script type="text/javascript">';
	  $response .= 'self.close();';
	  $response .= '</script>';

	  return new Response($response);

	}
      else
	{
	  return $this->render('RTSCraftMainBundle:Admin:login.html.twig');
	}
    }

    public function loginBackAction()
    {
      //called after submitting the form
      $request = $this->get('request');

      $pwd = "";

      // change password
      if ($request->getMethod() == 'POST')
	{
	  //get the data submitted
	  $pwd = $request->request->get('pwd');
	}

      $pwd = md5($pwd);

      //FIXME : there is only 1 user, the admin ...
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:User');
      $users = $rep->findUser();

      //$users is an array ... of 1 element. Get the first element.
      if (!empty($users))
	{
	  $user = reset($users);
	  $passindb = $user->getPassword();

	  if ($passindb != $pwd)
	    {
	      //error !
	      $error = 'Incorrect password.';
	      return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error));
	    }
	}
	else
	  {
	    $error = 'Server error : no User found in database. Did you launch the install procedure ?';
	    return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error, 'code' => '103'));
	  }

      // ok : update session variables
      $this->auth_ok();

      $response = '<script type="text/javascript">';
      $response .= 'window.opener.location.reload();';
      $response .= 'self.close();';
      $response .= '</script>';
      echo $response;

      return new Response('ok');

      //return $this->render('RTSCraftMainBundle:Default:index.html.twig', array('is_auth' => true, 'render' => 'home'));
    }

    public function adminpwdAction()
    {
      $rep = $this->getDoctrine()->getRepository('RTSCraftMainBundle:User');
      $users = $rep->findUser();
      $pwd = "";

      if (!empty($users))
	{
	  /* there is already an user in database ... */
	  $error = "Already installed ...";
	  return $this->render("RTSCraftMainBundle:Common:error.html.twig", array('error' => $error, 'code' => '105'));
	}

      $request = $this->get('request');
      if ($request->getMethod() == 'POST')
	{
	  //get the data submitted
	  $pwd = $request->request->get('pwd');
	  $pwd2 = $request->request->get('pwd2');
	}
      else
	{
	  $error = "No data submitted";
	  return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error, 'code' => '106'));
	}

      if ($pwd != $pwd2)
	{
	  $error = "Password entered are different";
	  return $this->render('RTSCraftMainBundle:Common:error.html.twig', array('error' => $error, 'code' => '111'));
	}

      $pwd = md5($pwd);

      $user = new User();
      $user->setLogin('admin');
      $user->setPassword($pwd);

      /* Insert into database */
      $em = $this->getDoctrine()->getEntityManager();
      $em->persist($user);
      $em->flush();

      /* set session variables */
      $this->auth_ok();

      return $this->render('RTSCraftMainBundle:Admin:install_ok.html.twig');
    }

    public function disconnectAction()
    {
      $session = $this->get('session');

      if ($session != null)
	{
	  $session->set('isAdmin', false);
	  $session->set('timeout', time());
	}

      echo '<script type="text/javascript">window.location.reload()</script>';
      return new Response('ok');
    }

    /* Called after admin authentication successful */
    private function auth_ok()
    {
      $session = $this->get("session");

      /* Timeout default is 30 minutes (i.e 1800 seconds) */
      $session->set("isAdmin", true);
      $session->set("timeout", time() + 30 * 60);
    }
}
